<template>
	<view class="page-container">
		<!-- 主内容区 -->
		<view class="main-content">
			<!-- 角色列表 -->
			<view class="role-list">
				<view class="role-item" v-for="(item, index) in roles" :key="index" @click="selectRole(index)"
					:class="{ 'selected': currentRoleIndex === index, 'is-default': item.isDefault == 1 }">
					<div class="role-icon" :style="{'background-color': item.isDefault == '1' ? '#10B981' : '#3B82F6'}">
						<van-icon :name="item.icon" color="#fff" size="30px" />
						<!-- 默认角色标识 -->
						<view class="default-badge" v-if="item.isDefault == 1">
							<van-icon name="check" color="#fff" size="14px" />
						</view>
					</div>

					<div class="role-info">
						<div class="role-name-container">
							<h3 class="role-name">{{ item.name }}</h3>
							<view class="default-tag" v-if="item.isDefault == 1">默认</view>
						</div>
						<p class="role-desc">{{ item.description }}</p>
					</div>

					<!-- 操作按钮区域 -->
					<div class="role-actions">
						<van-icon name="edit" size="20" class="action-icon edit-icon" @click.stop="handleEdit(item)" />
						<van-icon :name="item.isDefault == '1' ? 'star' : 'star-o'" size="20" class="action-icon default-icon"
							@click.stop="setAsDefault(item)" v-if="item._id != '68db8479c3b5c9ccb0dfdf38'" />
						<van-icon name="delete" size="20" class="action-icon delete-icon"
							v-if="item._id != '68db8479c3b5c9ccb0dfdf38'" @click.stop="handleDelete(item)" />
					</div>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-if="roles.length === 0">
					<van-empty description="暂无角色数据" />
				</view>
			</view>
		</view>

		<!-- 底部按钮区域 -->
		<view class="bottom-area">
			<button class="submit-btn" @click="showAddRolePopup">
				新增角色
			</button>
		</view>

		<!-- 新增角色弹窗 -->
		<van-popup :show="showAddPopup" position="top" @click-overlay="showAddPopup = false">
			<view class="popup-container">
				<view class="form-group">
					<van-field v-model="newRole.name" @change="inputChange($event , 'name')" label="角色名称"
						placeholder="请输入角色名称" :border="true" required />

					<van-field v-model="newRole.description" @change="inputChange($event , 'description')" label="角色描述"
						placeholder="请输入角色描述" :border="true" type="textarea" rows="4" />

					<van-field v-model="newRole.icon" label="角色图标" placeholder="选择角色图标" :border="true">
						<template #input>
							<van-icon :name="newRole.icon" size="24" @click="showIconPicker = true" />
						</template>
					</van-field>
					
					<van-field v-model="newRole.icon" label="是否默角色" placeholder="选择角色图标" :border="true">
						<template #input>
							<van-radio-group :value="newRole.isDefault" @change="isDefaultChange">
							 <div style="display: flex;">
								 <van-radio name="1">是</van-radio>
								 <van-radio name="2" style="margin-left: 15px;">否</van-radio>
							 </div>
							</van-radio-group>
						</template>
					</van-field>
				</view>

				<view class="popup-buttons">
					<button class="cancel-btn" @click="showAddPopup = false">
						取消
					</button>
					<button class="save-btn" @click="saveNewRole">
						保存
					</button>
				</view>
			</view>
		</van-popup>

		<!-- 图标选择器弹窗 -->
		<van-popup :show="showIconPicker" position="bottom" @click-overlay="showIconPicker = false">
			<view class="icon-picker-container">
				<h3 class="popup-title">选择图标</h3>
				<view class="icons-grid">
					<view class="icon-item" v-for="icon in iconList" :key="icon" @click="selectIcon(icon)">
						<van-icon :name="icon" size="28" />
						<span>{{ icon }}</span>
					</view>
				</view>
			</view>
		</van-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 当前选中的角色索引
				currentRoleIndex: 0,
				// 角色列表
				roles: [],
				// 新增角色弹窗显示状态
				showAddPopup: false,
				// 颜色选择器显示状态
				showColorPicker: false,
				// 图标选择器显示状态
				showIconPicker: false,
				// 新角色表单数据
				newRole: {
					name: '',
					description: '',
					icon: 'user',
					isDefault: '2' // 新增是否设为默认
				},
				// 可选图标列表
				iconList: ["arrow", "arrow-left", "arrow-up", "arrow-down", "success", "cross", "plus", "minus", "fail",
					"circle", "location-o", "like-o", "star-o", "phone-o", "setting-o", "fire-o", "coupon-o", "cart-o",
					"shopping-cart-o", "cart-circle-o", "friends-o", "comment-o", "gem-o", "gift-o", "point-gift-o",
					"send-gift-o", "service-o", "bag-o", "todo-list-o", "balance-list-o", "close", "clock-o",
					"question-o", "passed", "add-o", "gold-coin-o", "info-o", "play-circle-o", "pause-circle-o",
					"stop-circle-o", "warning-o", "phone-circle-o", "music-o", "smile-o", "thumb-circle-o",
					"comment-circle-o", "browsing-history-o", "underway-o", "more-o", "video-o", "shop-o",
					"shop-collect-o", "share-o", "chat-o", "smile-comment-o", "vip-card-o", "award-o", "diamond-o",
					"volume-o", "cluster-o", "wap-home-o", "photo-o", "gift-card-o", "expand-o", "medal-o",
					"good-job-o", "manager-o", "label-o", "bookmark-o", "bill-o", "hot-o", "hot-sale-o", "new-o",
					"new-arrival-o", "goods-collect-o", "eye-o", "delete-o", "font-o", "contact-o", "notes-o",
					"records-o", "cash-back-record-o", "newspaper-o", "discount-o", "completed-o", "user-o",
					"description-o", "balance-o", "refund-o", "birthday-cake-o", "orders-o", "tv-o", "envelop-o",
					"flag-o", "flower-o", "filter-o", "bar-chart-o", "chart-trending-o", "brush-o", "bullhorn-o",
					"hotel-o", "cashier-o", "warn-o", "calendar-o", "bulb-o", "user-circle-o", "desktop-o", "apps-o",
					"home-o", "back-top", "search", "points", "edit", "qr", "qr-invalid", "closed-eye", "down", "scan",
					"revoke", "free-postage", "certificate", "logistics", "after-sale", "exchange", "upgrade",
					"ellipsis", "sign", "failure", "ecard-pay", "peer-pay", "balance-pay", "credit-pay", "debit-pay",
					"cash-on-deliver", "other-pay", "tosend", "pending-payment", "paid", "aim", "idcard", "replay",
					"shrink", "shield-o", "guide-o", "cash-o", "link-o", "miniprogram-o", "list-switch",
					"list-switching", "location", "like", "star", "phone", "setting", "fire", "coupon", "cart",
					"shopping-cart", "cart-circle", "friends", "comment", "gem", "gift", "point-gift", "send-gift",
					"service", "bag", "todo-list", "balance-list", "clear", "clock", "question", "checked", "add",
					"gold-coin", "info", "play-circle", "pause-circle", "stop-circle", "warning", "phone-circle",
					"music", "smile", "thumb-circle", "comment-circle", "browsing-history", "underway", "more",
					"video", "shop", "shop-collect", "share", "chat", "smile-comment", "vip-card", "award", "diamond",
					"volume", "cluster", "wap-home", "photo", "gift-card", "expand", "medal", "good-job", "manager",
					"label", "bookmark", "bill", "hot", "hot-sale", "new", "new-arrival", "goods-collect", "eye",
					"delete", "font", "contact", "notes", "records", "cash-back-record", "newspaper", "discount",
					"completed", "user", "description", "wechat", "wechat-pay", "wechat-moments", "qq", "alipay",
					"weibo", "photograph", "youzan-shield", "umbrella-circle", "bell", "printer", "map-marked", "card",
					"add-square", "live", "lock", "audio", "graphic", "column", "invitation", "play", "pause", "stop",
					"weapp-nav", "ascending", "descending", "bars", "wap-nav", "enlarge", "photo-fail", "sort"
				]
			};
		},

		onShow() {
			// 页面显示时加载角色列表
			this.loadRoles();
		},

		methods: {
			// 加载角色列表数据
			async loadRoles() {
				try {
					const result = await this.$axios('overallSituation', {
						state: "look",
						databaseName: "role",
						sort:"asc"
					}, true);
					if (result.code === 200) {
						this.roles = result.data || [];

						// 如果有默认角色，选中默认角色
						const defaultRoleIndex = this.roles.findIndex(role => role.isDefault == 1);
						if (defaultRoleIndex !== -1) {
							this.currentRoleIndex = defaultRoleIndex;
						} else if (this.roles.length > 0 && this.currentRoleIndex >= this.roles.length) {
							// 如果没有默认角色，选中第一个
							this.currentRoleIndex = 0;
						}
					}
				} catch (error) {
					this.$showToast('加载角色失败')
				}
			},

			inputChange(e, key) {
				this.newRole[key] = e.detail
			},

			// 显示新增角色弹窗
			showAddRolePopup() {
				// 重置表单
				this.newRole = {
					name: '',
					description: '',
					icon: 'user',
					isDefault: '2'
				};
				this.showAddPopup = true;
			},
			
			isDefaultChange(e){
				this.newRole.isDefault = e.detail
			},

			// 选择图标
			selectIcon(icon) {
				this.newRole.icon = icon;
				this.showIconPicker = false;
			},

			// 保存新角色
			async saveNewRole() {
				// 表单验证
				if (!this.newRole.name.trim()) {
					this.$showToast('请输入角色名称')
					return;
				}

				try {
					// 如果设为默认，需要先取消其他角色的默认状态
					if (this.newRole.isDefault == 1 && this.roles.length > 0) {
						await this.clearDefaultRoles();
					}

					// 准备提交参数
					const params = {
						...this.newRole,
						state: 'add',
						createTime: this.$getTime('yyyy-MM-DD'),
						databaseName: 'role'
					};

					// 调用接口保存
					const result = await this.$axios('overallSituation', params);

					if (result.code === 200) {
						this.$showToast('角色添加成功')

						// 关闭弹窗
						this.showAddPopup = false;

						// 重新加载角色列表
						this.loadRoles();
					}
				} catch (error) {
					this.$showToast('保存失败，请重试')
				}
			},

			// 设为默认角色
			async setAsDefault(role) {
				// 如果已经是默认角色，点击取消默认
				if (role.isDefault == 1) {
					uni.showModal({
						title: '取消默认',
						content: `确定要取消"${role.name}"的默认角色状态吗？`,
						success: async (res) => {
							if (res.confirm) {
								await this.updateDefaultStatus(role._id, false);
							}
						}
					});
					return;
				}

				// 如果不是默认角色，设为默认
				uni.showModal({
					title: '设为默认',
					content: `确定要将"${role.name}"设为默认角色吗？`,
					success: async (res) => {
						if (res.confirm) {
							// 先清除其他角色的默认状态
							await this.clearDefaultRoles();
							// 再设置当前角色为默认
							await this.updateDefaultStatus(role._id, true);
						}
					}
				});
			},

			// 清除所有角色的默认状态
			async clearDefaultRoles() {
				const defaultRoles = this.roles.filter(role => role.isDefault == 1);
				if (defaultRoles.length > 0) {
					for (const role of defaultRoles) {
						await this.updateDefaultStatus(role._id, false, true);
					}
				}
			},

			// 更新角色默认状态
			async updateDefaultStatus(roleId, isDefault, silent = false) {
				try {
					const params = {
						_id: roleId,
						isDefault: isDefault ? '1' : '2',
						state: 'update',
						databaseName: 'role'
					};

					const result = await this.$axios('overallSituation', params);

					if (result.code === 200) {
						if (!silent) {
							this.$showToast(isDefault == 1 ? '已设为默认角色' : '已取消默认角色');
						}
						// 重新加载角色列表
						this.loadRoles();
					}
				} catch (error) {
					this.$showToast('操作失败，请重试');
				}
			},

			// 选择角色
			selectRole(index) {
				this.currentRoleIndex = index;
			},

			// 编辑角色
			handleEdit(item) {
				const role = item
				this.$router(`/subPackages2/pages/role/edit?roleId=${role._id}`);
			},

			// 删除角色
			async handleDelete(item) {
				const role = item
				// 如果是默认角色，删除前提示
				if (role.isDefault == 1) {
					this.$showToast('默认角色不能删除，请先取消其默认状态')
					return;
				}

				uni.showModal({
					title: '确认删除',
					content: `确定要删除角色"${role.name}"吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								const params = {
									_id: role._id,
									state: 'delete',
									databaseName: 'role'
								};

								const result = await this.$axios('overallSituation', params);

								if (result.code === 200) {
									this.$showToast('角色已删除')

									// 重新加载角色列表
									this.loadRoles();
								}
							} catch (error) {
								this.$showToast('删除失败，请重试')
							}
						}
					}
				});
			},
		}
	};
</script>

<style scoped>
	/* 基础样式 */
	* {
		box-sizing: border-box;
		margin: 0;
		padding: 0;
	}

	.page-container {
		min-height: 100vh;
		background-color: #f9fafb;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
		color: #111827;
		display: flex;
		flex-direction: column;
	}

	/* 主内容区 */
	.main-content {
		flex: 1;
		padding: 24px 16px;
		overflow-y: auto;
	}

	/* 角色列表 */
	.role-list {
		display: flex;
		flex-direction: column;
		gap: 12px;
	}

	/* 空状态 */
	.empty-state {
		padding: 60px 20px;
		text-align: center;
	}

	/* 角色项 */
	.role-item {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 16px;
		padding: 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
		transition: all 0.3s ease;
	}

	.role-item:hover {
		box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
	}

	.role-item.selected {
		border: 2px solid #3b82f6;
		background-color: #f0f9ff;
	}

	/* 默认角色样式 */
	.role-item.is-default {
		border: 2px solid #10B981;
	}

	.role-item.is-default:hover {
		box-shadow: 0 6px 16px rgba(16, 185, 129, 0.15);
	}

	/* 角色图标 */
	.role-icon {
		width: 52px;
		height: 52px;
		border-radius: 12px;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 16px;
		flex-shrink: 0;
		position: relative;
	}

	/* 默认角色徽章 */
	.default-badge {
		position: absolute;
		bottom: -4px;
		right: -4px;
		width: 24px;
		height: 24px;
		background-color: #10B981;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 2px solid white;
	}

	/* 角色信息 */
	.role-info {
		flex: 1;
	}

	.role-name-container {
		display: flex;
		align-items: center;
		gap: 8px;
		margin-bottom: 4px;
	}

	.role-name {
		font-size: 18px;
		font-weight: 600;
		color: #111827;
	}

	/* 默认角色标签 */
	.default-tag {
		background-color: #10B981;
		color: white;
		font-size: 12px;
		padding: 2px 8px;
		border-radius: 12px;
		font-weight: 500;
		animation: pulse 2s infinite;
	}

	@keyframes pulse {
		0% {
			box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4);
		}

		70% {
			box-shadow: 0 0 0 6px rgba(16, 185, 129, 0);
		}

		100% {
			box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
		}
	}

	.role-desc {
		font-size: 14px;
		color: #6b7280;
		line-height: 1.4;
	}

	/* 操作按钮区域 */
	.role-actions {
		display: flex;
		gap: 16px;
		margin-left: 12px;
		padding-left: 12px;
		border-left: 1px solid #f1f5f9;
	}

	.action-icon {
		cursor: pointer;
		transition: all 0.2s ease;
	}

	.action-icon:hover {
		transform: scale(1.1);
	}

	.edit-icon {
		color: #3b82f6;
	}

	/* 默认角色按钮样式 */
	.default-icon {
		color: #F59E0B;
	}

	.default-icon.active {
		color: #D97706;
	}

	.delete-icon {
		color: #ef4444;
	}

	/* 底部按钮区域 */
	.bottom-area {
		padding: 16px;
		background-color: #fff;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
	}

	/* 提交按钮 */
	.submit-btn {
		width: 100%;
		height: 48px;
		background-color: #3b82f6;
		color: #fff;
		border: none;
		border-radius: 16px;
		font-size: 16px;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
	}

	.submit-btn:hover {
		background-color: #2563eb;
		transform: translateY(-2px);
		box-shadow: 0 6px 16px rgba(59, 130, 246, 0.2);
	}

	/* 弹窗样式 */
	.popup-container {
		height: 100%;
		padding: 20px;
		display: flex;
		flex-direction: column;
	}

	.popup-title {
		font-size: 18px;
		font-weight: 600;
		margin-bottom: 20px;
		color: #111827;
		padding-bottom: 8px;
		border-bottom: 1px solid #f1f5f9;
	}

	.form-group {
		flex: 1;
		overflow-y: auto;
	}

	/* 颜色选择器 */
	.color-picker {
		width: 36px;
		height: 36px;
		border-radius: 6px;
		border: 1px solid #e2e8f0;
	}

	/* 弹窗按钮区域 */
	.popup-buttons {
		display: flex;
		gap: 12px;
		margin-top: 20px;
	}

	.cancel-btn,
	.save-btn {
		flex: 1;
		height: 44px;
		border-radius: 12px;
		font-size: 16px;
		font-weight: 500;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.cancel-btn {
		background-color: #f3f4f6;
		color: #6b7280;
	}

	.save-btn {
		background-color: #3b82f6;
		color: #fff;
	}

	/* 图标选择器样式优化 */
	.icon-picker-container {
		height: 70vh;
		display: flex;
		flex-direction: column;
		padding: 10px;
		box-sizing: border-box;
	}

	.icons-grid {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		/* 固定4列布局 */
		gap: 14px;
		margin-top: 16px;
		overflow-y: auto;
	}

	.icon-item {
		width: 20%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 16px 8px;
		box-sizing: border-box;
		border-radius: 12px;
		background-color: #f9fafb;
		cursor: pointer;
		transition: all 0.2s ease;
		min-height: 80px;
		/* 固定高度确保对齐 */
		position: relative;
	}

	/* 选中状态样式 */
	.icon-item.selected::after {
		content: '';
		position: absolute;
		top: 4px;
		right: 4px;
		width: 16px;
		height: 16px;
		background-color: #3b82f6;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		font-size: 10px;
	}

	.icon-item:hover {
		background-color: #f0f9ff;
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1);
	}

	.icon-item van-icon {
		margin-bottom: 8px;
		color: #374151;
	}

	.icon-item span {
		font-size: 12px;
		color: #6b7280;
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 100%;
		padding: 0 4px;
	}
</style>